<?php
/**
 * @Author:      zk
 * @DateTime:    18-7-11 下午5:19
 * @Description: 用于 OA 系统用户的登录登出
 */
class OAUserController extends BaseController {

    public function __construct(){
        header('Access-Control-Allow-Origin:*');	//解决资源跨域问题
	header('Access-Control-Allow-Credentials', 'true');
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-12 上午10:41
     * @Description: 验证token 
     * @param string $token             用户token
     * @link http://api.anhui.com/oa/user/checkToken?token=e092cdea4c09828f8c8b4228831c1a0b
     * @return string
     */
    public function checkToken(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                $response['result'] = $validator->messages()->all();
                break;
            }
            $oa_user = $this->verificationOAUserToken(Input::get("token"), $response);
            if(is_null($oa_user)){
                break;
            }
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/checkToken', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-7-11 下午5:27
     * @Description:     OA 用户登陆
     * @param string $username          用户账号
     * @param string $passwd            用户密码
     * @link http://api.anhui.com/oa/user/login?username=admin&passwd=123456
     * @return string
     */
    public function login(){
        $validator = Validator::make(Input::all(),
            array(
                'username' => 'required',
                'passwd' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get('oa_error.login_args_error_210001');
                break;
            }
            $username   = Input::get('username');               //用户名
            $passwd     = Common::make(Input::get('passwd'));   //密码
            
            $oa_user = OAUser::findUserByUP($username, $passwd);    //验证密码
            if(!is_null($oa_user)){
                if($oa_user->status != 1){
                    $response = Lang::get('oa_error.login_user_status_error_210002');
                    break;
                }
                $user_id = $oa_user->id;
                //$oa_user_resource = OAResource::getResourceByUserid($user_id);      //获取用户资源信息
                $oa_usermenu = OAResource::getMenuByUserid($user_id);               //获取用户的 菜单、目录、资源信息
                try {
                    OAUserToken::where('oa_user_id', $user_id)->delete();
                    $oa_token = new OAUserToken();
                    $oa_token->oa_user_id = $user_id;
                    $oa_token->token = md5($username. time(). rand(0, 100));
                    $oa_token->created_at = Common::num2DateTime(time());
                    $oa_token->out_time_at = Common::num2DateTime(time() + Config::get("oa_user.token_time_out"));
                    $oa_token->save();

                    // 添加操作日志     end
                }catch (Exception $e){
                    Log::info('info', ['system' => 'oa', 'event' => 'user/login', 'input' => Input::all(), 'exception' => $e]);
                    $response = Lang::get('oa_error.login_create_token_error_210005');
                    break;
                }

                try {
                    OAOpLog::writeLog('user/login', 4, '登录', '', json_encode($oa_user), $user_id);
                } catch (Exception $e) {
                    Log::info('info', ['system' => 'oa', 'event' => 'user/login', 'input' => Input::all(), 'exception' => $e]);
                    $response = Lang::get('oa_error.approval_type_create_error_221002');
                    break;
                }
            }else{
                $response = Lang::get('oa_error.login_user_name_pwd_error_210003');
                break;
            }
            
            //组织返回
            $response = [
                'code' => 0,
                'msg' => 'ok',
                'result' => [
                    'id' => $user_id,
                    'hrm_user_id' => $oa_user->hrm_user_id,
                    'token' => $oa_token->token,
                    'out_time_at' => $oa_token->out_time_at,
                    'user_name' => $oa_user->user_name,
                    'real_name' => $oa_user->real_name,
                    'status' => $oa_user->status,
                    'updated_at' => ''.$oa_user->updated_at,
                    'created_at' => ''.$oa_user->created_at,
                    //'user_resource' => $oa_user_resource,
                    'user_menu' => $oa_usermenu,
                ],
            ];
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/login', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-12 下午2:15
     * @Description: OA 用户登出
     * @param string $token             用户token
     * @link http://api.anhui.com/oa/user/logout?token=e092cdea4c09828f8c8b4228831c1a0b
     * @return string
     */
    public function logout(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok',);
        do {
            if ($validator->fails()) {
                $response = Lang::get('oa_error.token_error_210009');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            try{
                OAUserToken::where('oa_user_id', $oa_user->id)->delete();

            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'user/logout', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.token_clean_error_210010');
                break;
            }

            try {
                OAOpLog::writeLog('user/logout', 5, '登出', '', json_encode($oa_user), $oa_user->id);         // 添加操作日志     end
            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'user/logout', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_type_create_error_221002');
                break;
            }
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/logout', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-12 下午2:27
     * @Description: 获取用户信息
     * @param string $token             用户token
     * @link http://api.anhui.com/oa/user/userInfo?token=e0a15e100b066739e0c15bc83120b731
     * @return string
     */
    public function userInfo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id = $oa_user->id;
            $user_info = OAUser::getUserById($user_id);
            if(!$user_info){
                $response = Lang::get('oa_error.user_not_exist_210007');
                break;
            }
            $result = OAUser::getUserInfo($user_id);
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/userInfo', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /*
     * @Author:      zk
     * @DateTime:    18-7-12 下午2:15
     * @Description: 修改密码
     * @param string $token             用户token
     * @param string $passwd            新密码
     * @param string $old_passwd        原密码
     * @link http://api.anhui.com/oa/user/modifyPwd?token=e092cdea4c09828f8c8b4228831c1a0b&passwd=1234567&old_passwd=123456
     */
    public function modifyPwd(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'passwd' => 'required',
                'old_passwd' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                $response['result'] = $validator->messages();
                break;
            }
            $token      = Input::get('token');
            $passwd     = Common::make(Input::get('passwd'));       //新密码
            $old_passwd = Common::make(Input::get('old_passwd'));   //原密码
            
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(!is_null($oa_user)){
                if($oa_user->password != $old_passwd && $oa_user->password != strtoupper($old_passwd)){
                    $response = Lang::get('oa_error.user_passwd_error_210011');
                    break;
                }
                if($oa_user->status != 1){
                    $response = Lang::get('oa_error.login_user_status_error_210002');
                    break;
                }
                $oa = OAUser::find($oa_user->id);
                $op_old_data = json_encode($oa);
                $oa->password = $passwd;
                $oa->updated_at = Common::num2DateTime(time());
                $oa->updated_by = $oa_user->id;
                $oa->save();
            }else{
                $response = Lang::get('oa_error.user_not_exist_210007');
                break;
            }
    
            try{
                OAUserToken::where('oa_user_id', $oa_user->id)->delete();

            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'user/modifyPwd', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.token_clean_error_210010');
                break;
            }

            try {
                OAOpLog::writeLog('user/modifyPwd', 2, '修改密码', $op_old_data, json_encode($oa), $oa_user->id);
            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'user/modifyPwd', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_type_create_error_221002');
                break;
            }
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/modifyPwd', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /*
     * @Author:      zk
     * @DateTime:    18-7-14 下午12:55
     * @Description: 获取所有hrm平台的部门列表
     * @param string $token             用户token
     * @link http://api.anhui.com/oa/user/department?token=ce4bf71f44afe308adc8d7bdcc62abba
     */
    public function department(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                $response['result'] = $validator->messages();
                break;
            }
            $token      = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){
                break;
            }
            
            $list = HrmDepartment::getDepartmentByParentid(0);
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $list);
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/department', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
        /*
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                $response['result'] = $validator->messages();
                break;
            }
            $token      = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){
                break;
            }
            $parent_id  = Input::get('parent_id', 0);      //父级部门id
            $select_arr = [
                'department_id', 'parent_id', 'name', 'description',
            ];
            if($parent_id == 0){
                //首次加载展示父级和子级
                $parent_info = HrmDepartment::select($select_arr)
                        ->where('parent_id', $parent_id)
                        ->orderBy('department_id')
                        ->first();
                if($parent_info){
                    $child_list = HrmDepartment::select($select_arr)
                            ->where('parent_id', $parent_info->department_id)
                            ->orderBy('department_id')
                            ->get();
                    $parent_info->child_list = $child_list;
                } else {
                    $parent_info->child_list = [];
                }
            }else{
                //只显示子级
                $parent_info = HrmDepartment::select($select_arr)
                        ->where('parent_id', $parent_id)
                        ->orderBy('department_id')
                        ->get();
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $parent_info);
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/department', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
         */
    }
    
    /*
     * @Author:      zk
     * @DateTime:    18-7-14 下午2:55
     * @Description: 员工列表
     * @param string $token         用户token
     * @param int $department_id    部门id
     * @param string $search        查询条件
     * @param int $page             页码 [默认 1]
     * @param int $page_size        每页显示数据条数 [默认 25]
     * @link http://api.anhui.com/oa/user/employeeList?token=ce4bf71f44afe308adc8d7bdcc62abba
     * @link http://api.anhui.com/oa/user/employeeList?token=cd42ad78766754e9a663e4ed43b64c02&department_id=1&search=admin
     */
    public function employeeList() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'page' => 'integer',
                'page_size' => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $department_id  = Input::get('department_id', '');      //部门id
            $search         = Input::get('search', '');             //搜索名称
            $page           = Input::get('page', 1);                //页码 [默认 1]
            $page_size      = Input::get('page_size', 25);          //每页显示数据条数 [默认 25]
            
            $select_arr = [
                'hr_user.user_id AS hr_user_id', 'hr_user.real_name AS hr_user_name', 'hr_user.sex AS hr_sex', 
                'hr_user.email AS hr_email', 'hr_user.telephone AS hr_telephone',
                'hr_position.name AS hr_position_name', 'hr_position.department_id', 
                'hr_department.name AS hr_department_name', 
            ];
            
            $list = HrmUser::leftJoin('hr_position', 'hr_user.position_id', '=', 'hr_position.position_id')
                    ->leftJoin('hr_department', 'hr_position.department_id', '=', 'hr_department.department_id')
                    ->select($select_arr)
                    ->where('hr_user.status', 1)
                    ->orderBy('hr_user.user_id');
            if($department_id != ''){
                $list->where('hr_position.department_id', $department_id);
            }
            if($search != ''){
                $raw_sql = "hr_user.real_name like '%".$search."%' OR hr_user.telephone like '%".$search."%'";
                $list->whereRaw(DB::raw($raw_sql));
            }
            
            $count = $list->count();
            $list = $list->skip($page_size * ($page - 1))->take($page_size)->get()->toArray();
            $user_id_arr = [];  //hrm 平台用户id数组
            if(!empty($list)){
                foreach ($list as $v) {
                    $user_id_arr[] = $v['hr_user_id'];
                }
            }
            $oa_user_info = OAUser::getUserByHrmUserid($user_id_arr);
            foreach ($list as &$v) {
                if(isset($oa_user_info[$v['hr_user_id']])){
                    $v['oa_user_info'] = $oa_user_info[$v['hr_user_id']];
                }else{
                    $v['oa_user_info'] = [];
                }
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('couont' => $count, 'list' => $list));
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/employeeList', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-14 下午5:12
     * @Description: 添加/编辑 OA系统用户
     * @param string $token         用户token
     * @param string $user_name     OA系统登录名称
     * @param string $password      OA系统登录密码
     * @param int $hr_user_id       HRM平台用户id
     * @param string $real_name     用户真实姓名
     * @param int $id               OA系统用户id [编辑时必传]
     * @link: http://api.anhui.com/oa/user/storeOaUser?token=1ce108359a4965e9305bd39b8692a1af&user_name=OA登录名&password=123456&hr_user_id=123&real_name=真实姓名
     * @return string
     */
    public function storeOaUser(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_name' => 'required',
                'password' => 'required',
                'hr_user_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id    = $oa_user->id;                      //管理员id
            $user_name  = Input::get('user_name');           //OA系统登录名称
            $password   = Input::get('password');            //OA系统登录密码
            $hr_user_id = Input::get('hr_user_id');          //HRM平台用户id
            $real_name  = Input::get('real_name', '');       //用户真实姓名
            $id         = Input::get('id', '');              //OA系统用户id   
            
            //判断OA系统登录名是否已经存在
            $exist_user = OAUser::where('user_name', $user_name)
                    ->whereIn('status', [1, 2]);
            if($id != ''){
                $exist_user->where('id', '!=', $id);
            }
            $exist_user = $exist_user->first();
            if($exist_user){
                $response = Lang::get('oa_error.user_exist_error_211008');
                break;
            }

            if($id != ''){
                $user = OAUser::find($id);
                $old_data = json_encode($user);
                $desc_type = '编辑用户（修改密码）';
                $user->updated_at = Common::num2DateTime(time());
                $user->updated_by = $user_id;
                if($password != $user->password){
                    $user->password = Common::make($password);
                }
                $new_data = json_encode($user);
                $type = 2;
            } else {
                $user = new OAUser();
                $user->status = 1;
                $user->created_at = Common::num2DateTime(time());
                $user->created_by = $user_id;
                $user->password = Common::make($password);
                $desc_type = '编辑用户（添加oa用户）';
                $old_data = '';
                $new_data = json_encode($user);
                $type = 1;
            }
            $user->user_name = $user_name;
            $user->hrm_user_id = $hr_user_id;
            if($real_name != ''){
                $user->real_name = $real_name;
            }

            try {
                $user->save();
            }catch (Exception $e){
                Log::info('info', ['system' => 'oa', 'event' => 'user/storeOaUser', 'input' => Input::all(), 'exception' => $e]);
                if($id != ''){
                    $response = Lang::get('oa_error.user_update_status_error_211007');
                }else{
                    $response = Lang::get('oa_error.user_create_status_error_211006');
                }
                break;
            }

            try {
                OAOpLog::writeLog('user/storeOaUser', $type, $desc_type, $old_data, $new_data, $user_id);
            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'user/storeOaUser', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_type_create_error_221002');
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/storeOaUser', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-16 上午10:52
     * @Description: 修改OA系统用户状态
     * @param string $token             用户token
     * @param int $id                   用户id
     * @param int $status               状态值 (1:启用;2:停用;3:删除;)
     * @link: http://api.anhui.com/oa/user/status?token=cd42ad78766754e9a663e4ed43b64c02&id=2&status=2
     * @return string
     */
    public function status(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'status' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            
            $user_id    = $oa_user->id;                 //管理员id
            $id         = Input::get('id');
            $status     = Input::get('status');
            $update_data = [
                'status' => $status,
                'updated_at' => Common::num2DateTime(time()),
                'updated_by' => $user_id,
            ];
            $statusDesc = [1 => '启用', 2 => '停用', 3 => '删除'];
            $op_old_data = json_encode(OAUser::find($user_id));
            try {
                OAUser::where('id', $id)->update($update_data);
            }catch (Exception $e){
                Log::info('info', ['system' => 'oa', 'event' => 'user/status', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.user_update_status_error_211009');
                break;
            }

            try {
                $op_new_data = json_encode(OAUser::find($user_id));
                OAOpLog::writeLog('user/status', 2, $statusDesc[$status], $op_old_data, $op_new_data, $user_id);
            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'user/status', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_type_create_error_221002');
                break;
            }
            
            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/status', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-16 上午11:36
     * @Description: 组织架构获取用户详情
     * @param string $token             用户token
     * @param int $hr_user_id           hrm平台用户id
     * @link: http://api.anhui.com/oa/user/hrmUserDetails?token=cd42ad78766754e9a663e4ed43b64c02&hr_user_id=17
     * @return string
     */
    public function hrmUserDetails(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'hr_user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            
            $hr_user_id = Input::get('hr_user_id');
            $hr_user_info = HrmUser::getUserInfoById($hr_user_id);
            $oa_user_info = OAUser::getUserByHrmUserid([$hr_user_id]);
            if(!empty($oa_user_info)){
                $hr_user_info['oa_user_info'] = $oa_user_info[$hr_user_id];
            } else {
                $hr_user_info['oa_user_info'] = [];
            }
            
            $response = array('code' => 0, 'msg' => 'ok','result' => $hr_user_info);
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'user/hrmUserDetails', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

}